package com.eascs.admin.o2o.backFees.controller;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.backFees.entity.O2oBackFeesEntity;
import com.eascs.admin.o2o.backFees.service.O2oBackFeesService;
import com.eascs.admin.o2o.backfee.service.O2OComBankFeeService;
import com.eascs.admin.o2o.internal.util.BeanUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.service.O2oChargeSituationService;
import com.eascs.admin.o2o.o2ozx.serviceimpl.O2oZxServiceImpl;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UuidUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.vo.ModelResult;

@RestController
@RequestMapping("/rbackfees")
public class O2oBackFeesRestController extends BaseRestController {
	private static Logger logger = LoggerFactory.getLogger(O2oBackFeesRestController.class);
	@Autowired
	O2OComBankFeeService o2oComBankFeeService;
	@Reference
	ICustomerInfoService iCustomerInfoService;

	@Reference
	SysOrgService sysOrgService;
	
	@Reference
	CustomerService customerService;
	@Autowired
	O2oChargeSituationService o2oChargeSituationService;
	@Autowired
	O2oBackFeesService  o2oBackFeesService;
	@Autowired
	O2oZxServiceImpl o2oZxServiceImpl;
	/**
	 * @Description:
	 * 				<p>
	 *               退款管理,客户信息
	 *               </p>
	 * @author yy
	 * @date 2017年11月30日 下午7:40:40
	 * @version V1.0
	 */
	@RequestMapping("/checkBalance")
	public BaseRestResult<String> checkBalance(String idCard,String type) {
		
		CustomerEntity basic = customerService.queryCustomerEntityByIdCard(idCard);
		
		if(basic==null){
			return BaseRestResult.warn("客户信息不存在，请核实");
		}
		
		BigDecimal balance =o2oChargeSituationService.getFreezeBalanceByLoanId(basic.getCustomerId());
		String url = "backfees/checkBalance_view";
		ViewContext.put("balance", balance);
		ViewContext.put("type", type);//view
		ViewContext.put("basic", basic);
		
	
		return new HtmlRestResult(url);
	}

	/**
	 * @Description:
	 * 				<p>
	 *               退款管理, 退款信息
	 *               </p>
	 * @author yy
	 * @date 2017年11月30日 
	 * @version V1.0
	 */
	@RequestMapping("/detail")
	public BaseRestResult<String> detailInfo(String id, String type,String idCard) {
		O2oBackFeesEntity  o2oBackFees =o2oBackFeesService.queryById(id);
		CustomerEntity customer = customerService.queryCustomerEntityByIdCard(idCard);
		
		if(customer==null){
			return BaseRestResult.warn("客户信息不存在，请核实");
		}
		String url = "backfees/detail";
		if(StringUtil.isNotBlank(type)){
			type = type.trim();
		}
		
		if (("VIEW").equals(type)) {
			url = "backfees/detail_view";// loanManagement/loan_gs_info
		}
		
		if(o2oBackFees==null){
			o2oBackFees = new O2oBackFeesEntity();
			o2oBackFees.setLoanId(customer.getCustomerId());
			o2oBackFees.setLoanName(customer.getCustomerName());
			o2oBackFees.setDocumentNo(customer.getIdNumber());
		}
		
		
		ViewContext.put("id", id);
		ViewContext.put("entity", o2oBackFees);
		return new HtmlRestResult(url);
	}
	
	/**
	 * @Description:
	 * 				<p>
	 *               客户身份证和姓名是否一致
	 *               </p>
	 * @author yy
	 * @date 2017年7月14日 上午11:02:30
	 * @version V1.0
	 */
	@RequestMapping(value = "/checkBackfees")
	public BaseRestResult<?> checkLoan(String idCard,String name ) {
		idCard = idCard.trim();
		
		CustomerEntity basic = customerService.queryCustomerEntityByIdCard(idCard);
		
		
		BigDecimal balance =o2oChargeSituationService.getFreezeBalanceByLoanId(basic.getCustomerId());
		if(balance.compareTo(BigDecimal.ZERO)<0){
			return BaseRestResult.warn("account_balance");
		}
		
		if (basic == null) {
			return BaseRestResult.warn("is_no_user");
			
		} else{
			if(!(basic.getCustomerName().equals(name.trim())&&basic.getIdNumber().equals(idCard.trim()))) {
				return BaseRestResult.warn("user_mismatch");
			}
			//是否有个人账户id
			if(StringUtil.isBlank(basic.getAccountId())){
				return BaseRestResult.warn("no_user_account");
			}
			
		}
		return BaseRestResult.warn("success");

	}
	
	@RequestMapping(value = "/saveOrupdateBackfees")
	public BaseRestResult<?> saveOrupdateBackfees(O2oBackFeesEntity entity) {
		
		if(entity.getBackMoney()==null){
			return BaseRestResult.warn("退款金额不能为空");
		}
		
		BigDecimal balance =o2oChargeSituationService.getFreezeBalanceByLoanId(entity.getLoanId());
		
		if(entity.getBackMoney().compareTo(balance)>0){
			return BaseRestResult.warn("退款金额超出可用金额。");
		}
		
		if(entity.getBackMoney().compareTo(BigDecimal.ZERO)==0){
			return BaseRestResult.warn("退款金额不能为0");
		}
		
		if(entity.getBackNo()==null){ // 客户银行卡号
			return BaseRestResult.warn("客户银行卡号不能为空");
		}
		
		if(entity.getBackBank()==null){
			return BaseRestResult.warn("客户银行开户行不能为空");
		}
		
		if(entity.getBackType()==null){
			return BaseRestResult.warn("付款方式不能为空");
		}
		
		User user = UserHolder.getUser();
		ActOrgEntity actOrgEntity = null;
		
		
		if(entity.getId()==null){
			entity.setCreateDate(new Date());
			entity.setCreateId(user.getNo());
			entity.setCreateName(user.getCname());
			entity.setStatus(StatusContexts.O2O_NEW);
			entity.setIsDel(StatusContexts.O2O_NO);
			entity.setBillCode(o2oZxServiceImpl.buildCode("TX"));
			entity.setUniqueId(UuidUtil.generateShortUuid());
			ModelResult<ActOrgEntity>  s = sysOrgService.getUniquePlatformWithUser(user.getNo());
			if(s.isSuccess()){
				actOrgEntity = s.getModel();
			}else{
				return BaseRestResult.warn(s.getErrMsg());
				
			}
			//actOrgEntity = sysOrgService.getOrgByUnitNo(entity.getLtd());
			if(actOrgEntity!=null){
				entity.setLtdName(actOrgEntity.getOrgName());
				entity.setLtdCode(actOrgEntity.getUnitCode());
				entity.setLtd(actOrgEntity.getUnitNo());
			}
			
			int count = o2oBackFeesService.insert(entity);
			if(count<0){
				logger.error("添加失败");
				return BaseRestResult.warn("添加失败");
			}else{
				return BaseRestResult.info("保存成功").andRedirect(UrlHelper.build("/backfees/list_detail?id="+entity.getId()));
			}
		}else{
			O2oBackFeesEntity  entityj = o2oBackFeesService.queryById(entity.getId());
			
			if(entityj!=null){
				if(!StatusContexts.WFTYPE_STATUS_NEW.equals(entityj.getStatus()) ){
					return BaseRestResult.warn("该单不在新建状态下无法编辑！");
				}
			}
			
			BeanUtils.copyProperties(entity,entityj );
			
			int count = o2oBackFeesService.update(entityj);
			if(count<0){
				logger.error("更新失败");
				return BaseRestResult.warn("更新失败");
			}else{
				BaseRestResult.warn("更新成功");
			}
			return BaseRestResult.info("更新成功").andRedirect(UrlHelper.build("/backfees/list_detail?id="+entityj.getId()));
		}
		
	}
	
	/**
	 * @Description:
	 * 				<p>
	 *               删除个人退款
	 *               </p>
	 * @author yy
	 * @date 2017年12月05日 下午2:39:19
	 * @version V1.0
	 */
	@RequestMapping("/delete")
	public BaseRestResult<String> deleteO2oQYZx(String id) {
		O2oBackFeesEntity  entity = o2oBackFeesService.queryById(id);
		
		if(entity!=null){
			if(!StatusContexts.WFTYPE_STATUS_NEW.equals(entity.getStatus()) ){
				return BaseRestResult.warn("该单不在新建状态下无法删除！");
			}
		}
		
		entity.setIsDel(StatusContexts.O2O_YES);
		int i=o2oBackFeesService.update(entity);
		if (i > 0) {
			return BaseRestResult.info("删除成功！").andRedirect("/backfees/list");
		}
		return BaseRestResult.warn("删除失败！");
	}
	
	
	/**
	 * 打印退款单
	 * 
	 * @param billCode
	 *            贷款编码
	 * @param printType
	 *            打印类型NEW-新系统，OLD-老系统
	 * @return
	 */
	@RequestMapping(value = "/print")
	public HtmlRestResult print(String id) {
		// 审批详情
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置显示格式
		ViewContext.put("printDate", df.format(new Date()));
		O2oBackFeesEntity  entity = o2oBackFeesService.queryById(id);
		ViewContext.put("entity", entity);
		String approvUrl = "/wf/processNode/agreeInfo?referId="+entity.getId()+"&amp;processType=ACCOUNT_REFUND";
		ViewContext.put("approvUrl", approvUrl);
		return HtmlRestResult.popHtmlFragment("backfees/backfees_print");
	}
	
	
}
